<template>
  <div class="bind">
    <img style="border-radius: 40px;margin-top: 10px;" src="/static/img/logo.png" />
    <div>Walmart 礼品卡查询工具v{{ version }}</div>
    <!-- <template  v-if="emailAddress"> -->
    <!-- <van-cell title="邮箱">
      <template #right-icon>
        {{ emailAddress || "未登录" }}
      </template>
    </van-cell>
    <van-cell title="用户">
      <template #right-icon>
        {{ userName || "未登录" }}
      </template>
    </van-cell> -->
    <!-- </template> -->
    <van-field
        label="ip查询间隔"
        v-model="ptimeout"
        type="number"
        :disabled="loading"
        placeholder="ip查询间隔"
      >
      <template #right-icon>秒</template>
      </van-field>
    <div style="padding: 20px 10px; margin-top: 30px">
        <van-uploader
          :after-read="afterRead"
          accept="application/*"
          :before-read="beforeRead"
        >
          <van-button type="info" :loading="loading" round block
            >上传礼品卡</van-button
          >
        </van-uploader>
        <span class="msg">
          导入excel第一列是卡号，第二列pin码，<a
            href="javascript:;"
            @click="download"
            >下载模板</a
          >
        </span>
      
    </div>
  </div>
</template>

<script>
import { fetchUser, fetchGiftCard, exportExcel } from "./common";
import Excel from "exceljs";
export default {
  props: {
    version: String,
  },
  data() {
    return {
      emailAddress: "",
      userName: "",
      total: 0,
      ptimeout: "",
      loading: false,
    };
  },
  async created() {
    // this.fetchUser();
    this.emailAddress = (await this.$getItem("emailAddress")) || "";
    this.userName = (await this.$getItem("userName")) || "";
    console.log(await this.$getItem("ptimeout"))
    this.ptimeout = (await this.$getItem("ptimeout")) || "15";
    this.loading = (await this.$getItem("isRun")) || false;
    chrome.runtime.onMessage.addListener((req) => {
      if (req.type === "isRun") {
        this.loading = req.data;
      }
      if (req.type === "error") {
        this.$notify({
          type: "warning",
          message: req.data,
        });
      }
    });
  },
  watch: {
    async ptimeout () {
      console.log('xxxx', this.ptimeout)
      this.$setItem({
        "ptimeout": this.ptimeout
      });

      console.log('xxxx', await this.$getItem("ptimeout"))
    }
  },
  methods: {
    testHandle() {
      fetchGiftCard("6306016285340081", "2638").then((res) => {
        console.log("fetchGiftCard", res);
      });
    },
    gotoLogin() {
      chrome.tabs.create({ url: "https://www.walmart.com/account/login" });
    },
    download() {
      // 下载，需要打开下载中
      exportExcel([], "礼品卡导入模板.xls");
    },
    loadTable(buffer) {
      console.log(buffer);
      var workbook = new Excel.Workbook();
      workbook.xlsx.load(buffer).then((workbook) => {
        console.log(workbook);
        const sheetCount = workbook.sheetCount;
        console.log('Number of sheets:', sheetCount);
        try {
          const worksheet = workbook.getWorksheet(1);
          // 迭代工作表中具有值的所有行
          let data = [];
          worksheet.eachRow((row, rowNumber) => {
            // 去掉两行表头
            console.log(row.values);
            if (rowNumber > 1 && row.values[1] && row.values[2]) {
              // 重新组织数据，excel无论单元格还是行都是从1开始的
              const model = {
                cardNumber: row.values[1] + "",
                pin: row.values[2] + "",
                cardBalance: "",
                error: "",
              };
              data.push(model);
            }
          });
          console.log("data", data);
          if (data && data.length > 0) {
            var bg = chrome.extension.getBackgroundPage();
            bg.runData(data);
          } else {
            this.loading = false;
            this.$notify({
              type: "warning",
              message: "文件格式不正确或没数据",
            });
          }
        } catch (e) {
          console.error(e);
          this.loading = false;
          this.$notify({ type: "warning", message: "文件格式有问题" });
        }
      });
    },
    afterRead(options) {
      this.loading = true;
      console.log("options", options);
      const buffer = new FileReader();
      buffer.readAsArrayBuffer(options.file);
      buffer.onload = (e) => {
        this.loadTable(buffer.result);
      };
    },
    beforeRead(file) {
      console.log(file);
      if (file.name.indexOf(".xls") === -1) {
        this.$notify({ type: "warning", message: "请上传 xls 格式文件" });
        return false;
      }
      return true;
    },
    fetchUser() {
      return fetchUser().then((res) => {
        console.log("fetchUser", res);
        if (
          res.status == 200 &&
          res.data &&
          res.data.data &&
          res.data.data.account &&
          res.data.data.account.profile
        ) {
          let profile = res.data.data.account.profile;
          this.emailAddress = profile.emailAddress;
          this.userName = `${profile.firstName} ${profile.lastName}`;
        } else {
          this.emailAddress = "";
          this.userName = "";
          this.$notify("未登录 Walmart");
        }
        this.$setItem({
          emailAddress: this.emailAddress,
          userName: this.userName,
        });
      });
    },
  },
};
</script>

<style scoped>
.bind {
  padding: 10px;
}

.title {
  font-size: 18px;
  margin-top: 10px;
  margin-bottom: 11px;
}
.van-cell__title {
  text-align: left;
}

.van-cell__value {
  flex: 2;
}
.msg {
  font-size: 12px;
  color: #999;
}
</style>